package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.R;
import com.itheima.dao.AddressBookDao;
import com.itheima.pojo.User;
import com.itheima.service.UserService;

import com.itheima.util.SMSUtils;
import com.itheima.util.ValidateCodeUtils;
import io.netty.util.Timeout;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.TimeoutUtils;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.concurrent.TimeUnit;


@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    AddressBookDao addressBookDao;

    @Autowired
    RedisTemplate redisTemplate;

    //获取验证码
    @PostMapping("/sendMsg")
    public R usersSendMsg(@RequestBody User user, HttpServletRequest request) throws IOException {
        //手机号
        String phoneNumbers = user.getPhone();
        //随机生成验证码,长度为4位或者6位
        String code = String.valueOf(ValidateCodeUtils.generateValidateCode(6));
//        String signName = "阿里云短信测试";
//        String templateCode = "SMS_154950909";
//        SMSUtils.SendMag(signName, templateCode, phoneNumbers, code);
        log.info(code);
        //将验证码存入session中
//        request.getSession().setAttribute(phoneNumbers,code);
        redisTemplate.opsForValue().set(phoneNumbers,code,5, TimeUnit.MINUTES);

        //将手机号也存入session中，方便后续清楚验证码
//        request.getSession().setAttribute("phone",user.getPhone());
        redisTemplate.opsForValue().set("phone",user.getPhone(),5,TimeUnit.MINUTES);
        return R.success("验证码发送成功");


    }

    /**
     * 用户登录
     */

    @PostMapping("/login")
    public R login(@RequestBody User user,HttpServletRequest request){
        //获取session中的验证码
//        String code = (String) request.getSession().getAttribute(user.getPhone());
        String code = (String) redisTemplate.opsForValue().get(user.getPhone());
        if(!code.equals(user.getCode())){
            return R.error("验证码错误!!");
        }
        //判断手机号是否存在
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone,user.getPhone());
        User one = userService.getOne(wrapper);
        if(one == null){
            //用户不存在则添加数据库中
            userService.save(user);
        }
        //从数据库中取出用户id存入session中，在拦截器中判断用户是否登录
        LambdaQueryWrapper<User> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(User::getPhone,user.getPhone());
        User one2 = userService.getOne(wrapper);
        request.getSession().setAttribute("user",one2.getId());
        return R.success("登录成功");

    }

    /**
     * 用户退出
     */
    @PostMapping("/loginout")
    public R logout(HttpServletRequest request){

        //清除用户id
        request.getSession().removeAttribute("user");
        //清除验证码
//        String phone = (String) request.getSession().getAttribute("phone");
//        request.getSession().removeAttribute(phone);
        String phone = (String) redisTemplate.opsForValue().get("phone");
        redisTemplate.delete(phone);
        //清除手机号
//        request.getSession().removeAttribute("phone");

        redisTemplate.delete("phone");
        return R.success("退出成功");
    }

}
